// 引入express 框架
const express = require("express");

// 日志记录所需中间件
let morgan = require("morgan");
let path = require("path");
let rfs = require("rotating-file-stream");

// 引入解决post请求
let bodyParser = require("body-parser");

// 引入后台管理相关接口
const adminRouter = require("./api/admin/admin");
// 引入图片上传统一接口
const upload = require("./api/uploadApi");
// 引入前台相关接口
const clientRouter = require("./api/client/client");

const app = express();

// 创建日志写入流
let accessLogStream = rfs.createStream('access.log', {
  interval: '1d', // rotate daily
  path: path.join(__dirname, 'log')
});

//设置跨域访问
app.all("*", function (req, res, next) {
  //设置允许跨域的域名，*代表允许任意域名跨域
  res.header("Access-Control-Allow-Origin", req.headers.origin || '*');
  // //允许的header类型
  res.header("Access-Control-Allow-Headers", "Content-Type, Authorization, X-Requested-With");
  // //跨域允许的请求方式
  res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
  if (req.method == 'OPTIONS') {
    res.sendStatus(200);
  } else {
    next();
  }
})

// 请求日志
app.use(morgan('combined', { stream: accessLogStream }));

// 配置post 请求
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());

// 监听是后台管理的接口择跳转
app.use("/api/admin", adminRouter());
// 图片上传统一接口
app.use("/upload", upload())
// 前台
app.use("/api/", clientRouter());


app.listen(3000, (err) => {
  if(err) {
    console.log("服务启动失败：", err);
  }else {
    console.log("服务启动成功");
  }
})